from decimal import Decimal

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from areas.serializers import AreaViewSerializer
from goods.models import SKU
from orders.serializers import OrderSerializer, OrdersSerializer

# class OrderView(ListAPIView):
#     serializer_class = OrdersSerializer
#
#     # 重写get_object方法
#     def get_queryset(self):
#         # 从ｒｅｄｉｓ中获取数据
#         conn = get_redis_connection("cart")
#         user = self.request.user
#         # 获取数量
#         cart_count = conn.hgetall("cart_{}".format(user.id))
#         cart = {}
#         for sku_id, count in cart_count.items():
#             cart[int(sku_id)] = int(count)
#
#         # 查询出所有选中状态的ｓｋｕ对象
#         # 获取选中状态的数据
#         sku_ids=conn.smembers('cart_selected_%s' % user.id)
#
#         skus = SKU.objects.filter(id__in=sku_ids)
#         for sku in skus:
#             sku.count = cart[sku.id]
#         # 　指定运费
#         freight = Decimal("10.00")
#
#         return {"freight": freight, "skus": skus}
from users.models import Address


class OrderView(APIView):
    def get(self, request):
        # 从ｒｅｄｉｓ中获取数据
        conn = get_redis_connection("cart")
        user = self.request.user
        # 获取数量
        cart_count = conn.hgetall("cart_{}".format(user.id))
        cart = {}
        for sku_id, count in cart_count.items():
            cart[int(sku_id)] = int(count)

        # 查询出所有选中状态的ｓｋｕ对象
        # 获取选中状态的数据
        sku_ids = conn.smembers('cart_selected_%s' % user.id)

        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            sku.count = cart[sku.id]
        # 　指定运费
        freight = Decimal("10.00")
        ser = OrdersSerializer({"freight": freight, "skus": skus})

        return Response(ser.data)
